package org.openmore.platform.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.thoughtworks.xstream.XStream;
import io.swagger.annotations.*;
import org.openmore.common.enums.PaymentType;
import org.openmore.common.enums.Platform;
import org.openmore.platform.dto.common.BaseResponse;
import org.openmore.platform.pay.IAP.IAPPayService;
import org.openmore.platform.pay.WechatPayService;
import org.openmore.platform.pay.alipay.AliPayService;
import org.openmore.platform.pay.alipay.AlipayNotify;
import org.openmore.platform.utils.wechatUtils.MapEntryConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;


/**
 * THIS IS AUTO GENERATED SOURCE CODE
 * Created by org.openmore
 * on 2018-08-11
 */
@Api(value = "/PayNotify", tags = "PayNotify", description = "支付成功通知处理")
@RequestMapping(value = "/api/payNotify", produces = {APPLICATION_JSON_UTF8_VALUE})
@RestController
public class PayNotifyController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WechatPayService wechatPayService;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private IAPPayService iapPayService;

    @ApiOperation(value = "微信支付通知", response = BaseResponse.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：保存视频失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.POST, value = "/wechat/{tenantId}/callback")
    public BaseResponse getWechatPayNotify(HttpServletRequest request,
                                           @PathVariable @ApiParam(name = "应用ID")String tenantId) {

        logger.info("getWechatPayNotify");
        try{
            XStream magicApi = new XStream();
            magicApi.registerConverter(new MapEntryConverter());
            magicApi.alias("xml", Map.class);
            ServletInputStream in = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String sReqData = "";
            String itemStr = "";
            while (null != (itemStr = reader.readLine())) {
                sReqData += itemStr;
            }
            Map<String, Object> map = (Map<String, Object>) magicApi.fromXML(sReqData);
            String return_code = map.get("return_code") + "";
            String result_code = map.get("result_code") + "";
            if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
                String sign = map.get("sign") + "";//sign不参与验签
                String reSign = wechatPayService.getSign(map, PaymentType.WECHAT_MINIAPP, tenantId);
                if (sign.equals(reSign)) {
                    /*String orderNumber = (String) map.get("out_trade_no");
                    Long payPrice = Long.parseLong((String) map.get("total_fee"));
                    String payId = (String) map.get("transaction_id");*/
                    return BaseResponse.buildSuccessResponse(true);
                } else {
                    //return "FAIL";
                    return BaseResponse.buildSuccessResponse(false);
                }
            }
            //return "FAIL";
            return BaseResponse.buildSuccessResponse(false);
        }catch (IOException e){
            e.printStackTrace();
            //return "FAIL";
            return BaseResponse.buildSuccessResponse(false);
        }
    }
    @ApiOperation(value = "支付宝支付通知", response = BaseResponse.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：保存视频失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.POST, value = "/alipay/{tenantId}/callback")
    public BaseResponse getAliPayNotify(HttpServletRequest request,
                                        @PathVariable @ApiParam(name = "应用ID")String tenantId) {
        logger.info("getAliPayNotify");
        return aliPayService.paynotify(request, tenantId);
    }

    /**参考：https://www.jianshu.com/p/976fc6090cfa*/
    //@TokenAuthCheck
    @ApiOperation(value = "IAP支付后主动校验", response = BaseResponse.class)
    @ApiResponses(value = {@ApiResponse(code = 4000, message = "请求失败：保存视频失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/iap/{tenantId}/verify")
    public BaseResponse getIapPayVerify(@PathVariable @ApiParam(name = "应用ID")String tenantId,
                                        @RequestParam(required = false) @ApiParam(value = "userId或deviceToken") String userId,
                                        @RequestParam() @ApiParam(value = "支付平台（IPHONE、IPAD）", required = true) Platform platform,
                                        @RequestParam(required = false) @ApiParam(value = "趣平方内部订单号") String orderNumber,
                                        @RequestParam @ApiParam(value = "三方平台交易订单号")String transactionId,
                                        @RequestParam @ApiParam(value = "交易价格")Long payPrice,
                                        @RequestParam(required = false) @ApiParam(value = "校验体（base64字符串）")String payload) {
        logger.info("getIapPayVerify");

        if(StringUtils.isEmpty(userId)){
            return BaseResponse.buildFailResponse(400, "用户非法请求，请先登录");
        }
        return iapPayService.payVerify(tenantId, orderNumber, userId, transactionId, payPrice, payload, platform);
    }


}



